package com.jd.pet.service.impl;

import com.jd.basic.service.impl.BaseServiceImpl;
import com.jd.pet.domain.PetType;
import com.jd.pet.mapper.PetTypeMapper;
import com.jd.pet.service.IPetTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 业务实现类：
 */
@Service
@CacheConfig(cacheNames = "petType") // 统一配置
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {
    @Autowired
    private PetTypeMapper petTypeMapper;
    @Override
    @Transactional
    @CacheEvict(key = "'petType'") // 删除缓存
    public void add(PetType petType) {
        super.add(petType);
    }

    @Override
    @Transactional
    @CacheEvict(key = "'petType'") // 删除缓存
    public void update(PetType petType) {
        super.update(petType);
    }

    @Override
    @Transactional
    @CacheEvict(key = "'petType'") // 删除缓存
    public void del(Long id) {
        super.del(id);
    }

    @Override
    @Transactional
    @CacheEvict(key = "'petType'") // 删除缓存
    public void patchDel(Long[] ids) {
        super.patchDel(ids);
    }
    @Override
    @Transactional
    @Cacheable(key = "'petType'") // 写入缓存
    public List<PetType> petTypeTree() {
        return getPetTypeTree();
    }

    /**
     * 获取宠物类型树
     * @return
     */
    private ArrayList<PetType> getPetTypeTree() {
        // 查询所有宠物类型
        List<PetType> all = petTypeMapper.findAll();
        // 创建一个空map用id-部门表示部门
        HashMap<Long, PetType> map = new HashMap<>();
        // 对部门进行遍历放入map
        for (PetType petType : all) {
            map.put(petType.getId(), petType);
        }
        // 创建一个集合用来存树
        ArrayList<PetType> petTypeTree = new ArrayList<>();
        // 遍历判断如果没有上级部门即为顶级部门，直接放入
        for (PetType petType : all) {
            if (petType.getParentId() == null) {
                petTypeTree.add(petType);
            } else { // 不是顶级部门，查找上级部门
                Long parentId = petType.getParentId();
                // 找到父部门，将自己放入上级部门的children中
                PetType parentPetType = map.get(parentId);
                parentPetType.getChildren().add(petType);
            }
        }
        return petTypeTree;
    }
}
